package org.ekingstar.qd.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.ekingstar.qd.domain.Catalog;
import org.ekingstar.qd.domain.QdCompareCond;
import org.ekingstar.qd.domain.QdDomain;
import org.ekingstar.qd.domain.QdDomainDest;
import org.ekingstar.qd.domain.QdDomainDestId;
import org.ekingstar.qd.domain.QdFormula;
import org.ekingstar.qd.domain.QdMark;
import org.ekingstar.qd.domain.QdSimplemeasu;
import org.ekingstar.qd.domain.QdWhereClause;
import org.ekingstar.qd.service.CCatalogService;
import org.ekingstar.qd.service.CDomainService;
import org.ekingstar.utils.SysArgUtil;

import com.ekingstar.framework.domain.Function;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.framework.util.HibernateCallbackUtil;
import com.ekingstar.framework.util.Page;

public class CDomainServiceImpl implements CDomainService {
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	private  CCatalogService catalogService;
	public void setCatalogService(CCatalogService catalogService) {
		this.catalogService = catalogService;
	}
	
	//返回所有主题信息
	@SuppressWarnings("unchecked")
	public List<QdDomain> getDomainList(){
		return this.hibernateTemplate.find("from QdDomain ");
	}
	
	/**
	 * @descripte 根据主题类别，查询所有主题类别下的主题 
	 * @param strCatalogId 主题类别ID号
	 * @return QdDomain
	 */
	@SuppressWarnings("unchecked")
	public List<QdDomain> getDomainList(String strCatalogId){
		if(strCatalogId!=null && !"".equals(strCatalogId)){
			return this.hibernateTemplate.find("from QdDomain qdDomain where qdDomain.catalogId.catalogId='"+strCatalogId+"' order by qdDomain.orderId ");	
		}else{
			return this.hibernateTemplate.find("from QdDomain qdDomain where 1<1 ");
		}			
	}
	
	
	/**
	 * @descripte 根据主题类别和主题名称查询主题
	 * @param strCatalogId 主题类别ID号
	 * @param strKeyWord   主题名称
	 * @return QdDomain
	 */
	@SuppressWarnings("unchecked")
	public List<QdDomain> getDomainList(String strCatalogId,String strKeyWord){
		String hql = " from QdDomain qdDomain where 1=1 ";
		String condition = "";
		if(strCatalogId!=null && !"".equals(strCatalogId)){
			condition += " and qdDomain.catalogId.catalogId='"+strCatalogId+"' ";
		}
		
		if(strKeyWord!=null && !"".equals(strKeyWord)){
			condition += " and qdDomain.name like '%"+strKeyWord+"%' ";
		}
		
		if(condition==null  || "".equals(condition)){
			condition += " and 1<1  ";
		}
		
		hql+= condition+"  order by qdDomain.orderId ";
		
		return this.hibernateTemplate.find(hql);
	}
	
	
	/**
	 * @descripte 根据主题分类和主题审核状态显示主题信息
	 * @param  strCatalogId 主题类别ID号
	 * @param  nFlag        审核状态
	 * @return QdDomain
	 */
	@SuppressWarnings("unchecked")
	public List<QdDomain> getDomainList(String strCatalogId,int nFlag){
		String hql = " from QdDomain qdDomain where 1=1 ";
		String condition = "";
		if(strCatalogId!=null && !"".equals(strCatalogId)){
			condition += " and qdDomain.catalogId.catalogId='"+strCatalogId+"' ";
		}
		
		condition += " and qdDomain.TQdMark.id = "+nFlag;	
		
		if(condition==null  || "".equals(condition)){
			condition += " and 1<1  ";
		}
		
		hql+= condition+"  order by qdDomain.orderId ";
		List<QdDomain> r = this.hibernateTemplate.find(hql);
		return r;
	}
	
	/**
	 * @descripte 根据主题ID号获取主题信息 
	 * @param strDomainId 主题类别ID号
	 * @return QdDomain
	 */
	public QdDomain getDomain(String strDomainId){
		QdDomain qdDomain = null;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				qdDomain = (QdDomain)hibernateTemplate.get(QdDomain.class, strDomainId);
			}
		}catch(Exception e){
			qdDomain = null;
		}
		return qdDomain;			
	}
	
	/**
	 * @descripte 批量移动主题信息。
	 *    若目标分类与源分类相同，则给出提示，不予移动。
	 *    批量移动前先给出提示，若确定移动，则将选定的主题批量移动至目标分类。
	 *    若目标分类中已存在同名的主题，则同名主题将被忽略，不予移动，其他主题继续移动，移动后给出信息提示，信息内容包括成功移动主题数，忽略的主题数
	 * @param  strDomainId   被移动的主题ID集
	 * @param  strCatalogId  主题移至目标主题分类ID号
	 * @return String  成功移动主题数,忽略的主题数
	 */
	public String moveDomain(String[] strDomainId,String strCatalogId){
		String retStr = "";
		try{
			int unremove = 0;
			int remove = 0;
			
			if(strDomainId!=null && strDomainId.length>0 && strCatalogId!=null && !"".equals(strCatalogId.toString().trim())){
				/**
				 * @descript 获取移动到的主题类别和主题类别对应菜单
				 */
				Function function = null;
				Catalog catalogId = catalogService.getCatalog(strCatalogId.toString().trim());
				if(catalogId!=null && catalogId.getCatalogId()!=null && !"".equals(catalogId.getCatalogId().toString().trim())){
					if(catalogId.getFunctionId()!=null && !"".equals(catalogId.getFunctionId().toString().trim())){
						function = getFunction(catalogId.getFunctionId().toString().trim());
						if(function==null || function.getId()=="" || "".equals(function.getId().toString().trim())){
							function = this.reBuildFunction(catalogId);
							catalogId.setFunctionId(function.getId());
							this.hibernateTemplate.saveOrUpdate(catalogId);
						}
					}else{
						function = this.reBuildFunction(catalogId);
						catalogId.setFunctionId(function.getId());
						this.hibernateTemplate.saveOrUpdate(catalogId);
					}
				}
				
				for(int i=0;i<strDomainId.length;i++){
					//获取主题
					QdDomain qdDomain = (QdDomain)this.hibernateTemplate.get(QdDomain.class, strDomainId[i].toString());
					if(qdDomain!=null && qdDomain.getId()!=null){
						//判断目标主题类别和现主题类别是否相同
						if(strCatalogId == qdDomain.getCatalogId().getCatalogId() || strCatalogId.equals(qdDomain.getCatalogId().getCatalogId().toString().trim())){
							retStr = "目标分类与源分类相同，不予移动!,";
							break;
						}
						
						//判断目标主题类别下是否已存在相同名称的主题
						if(isExistsDomainByName(qdDomain.getName(), strCatalogId)>0){
							unremove++;
						}else{
							remove++;						
							//更新主题菜单信息
							Function dFunction = null;
							if(qdDomain.getFunctionId()!=null && !"".equals(qdDomain.getFunctionId().toString().trim())){
								dFunction = (Function)this.getFunction(qdDomain.getFunctionId().toString().trim());
								if(dFunction==null || dFunction.getId()=="" || "".equals(dFunction.getId().toString().trim())){
									dFunction = this.addFunction(qdDomain.getName(),strCatalogId);
								}
							}else{
								dFunction = this.addFunction(qdDomain.getName(), strCatalogId);
							}
							dFunction.setParent(function);
							hibernateTemplate.saveOrUpdate(dFunction);
							
							//更新主题信息
							qdDomain.setCatalogId(catalogId);
							qdDomain.setFunctionId(dFunction.getId());
							hibernateTemplate.saveOrUpdate(qdDomain);	
							
							//更新地址
							dFunction.setAddresss("/querythemes/qdDomainSearch!load4Init.action?strDomainId="+qdDomain.getId());
							hibernateTemplate.saveOrUpdate(dFunction);
						}
					}				
				}			
			}
			
			if(remove>0){
				retStr+="成功移动主题"+remove+"条记录,";
			}
			
			if(unremove>0){
				retStr+="忽略的主题"+remove+"条记录,";
			}
			
			if(retStr!=null && !"".equals(retStr)){
				retStr = retStr.substring(0,retStr.length()-1);
			}
		}catch(Exception e){
			e.printStackTrace();
			retStr = "移动主题失败,请联系管理员!";
		}
		
		return retStr;
	}
	
	
	
	/**
	 * @descripte 根据主题类别ID和主题名称，判断是否已经存在相同主题名称的主题，有返回1，否则返回-1
	 * @param  strName       主题名称
	 * @param  strCatalogId  主题分类ID号
	 * @return int
	 */
	@SuppressWarnings("unchecked")
	public int isExistsDomainByName(String strName,String strCatalogId){
		int retInt = -1;
		if(strName!=null && !"".equals(strName)){
			String hql = "from QdDomain qdDomain where qdDomain.name='"+strName+"' and qdDomain.catalogId.catalogId='"+strCatalogId+"' ";
			List l = this.hibernateTemplate.find(hql);
			if(l!=null && l.size()>0){
				retInt = 1;
			}			
		}		
		return retInt;		
	}
	
	
	
	
	/**
	 * @descripte 批量删除主题及其主题配置和授权信息，删除成功返回1否则返回-1
	 * @param  strDomainId   被删除主题信息ID集
	 * @return int
	 */
	public int delDomain(String[] strDomainId){
		int retInt = -1;
		try{
			if(strDomainId!=null && strDomainId.length>0){
				for(int i=0;i<strDomainId.length;i++){
					QdDomain qdDomain = (QdDomain)hibernateTemplate.get(QdDomain.class, strDomainId[i].toString().trim());
					if(qdDomain!=null && qdDomain.getId()!=null && !"".equals(qdDomain.getId().toString().trim())){
						//删除主题
						String delDomain = "delete from t_qd_domain where id ='"+qdDomain.getId().toString().trim()+"'";
						//删除主题和表关系
						String delRelation = "delete from t_qd_domain_dest where domainid ='"+qdDomain.getId().toString().trim()+"'";
						//删除表关系(主题表达式)
						String delFormula = "delete from t_qd_formula where domainid ='"+qdDomain.getId().toString().trim()+"'";
						//删除主题查询字段
						String delSimplemeasu = "delete from t_qd_simplemeasu where domainid ='"+qdDomain.getId().toString().trim()+"'";
						//删除主题过滤条件
						String delWhereClause = "delete from t_qd_where_clause where domainid ='"+qdDomain.getId().toString().trim()+"'";
						//删除查询字段
						String delComparecond =  "delete from t_qd_comparecond where domainid ='"+qdDomain.getId().toString().trim()+"'";
						//删除历史查询条件
						String delHiscon =  "delete from t_qd_hiscon where domainid ='"+qdDomain.getId().toString().trim()+"'";
						//删除发布查询字段
						String delDelopeComparecond = " delete from t_deploy_qd_comparecond where comparecond_id in (select id from t_qd_comparecond where domainid ='"+qdDomain.getId().toString().trim()+"')";					
						//删除发布主题查询显示列字段
						String delDelopeSimplemeasu = " delete from t_deploy_qd_simplemeasu where simplemeasu_id in (select id from t_qd_simplemeasu where domainid ='"+qdDomain.getId().toString().trim()+"')";
						//删除发布删除主题过滤条件
						String delDelopeWhereClause = " delete from t_deploy_qd_where_clause where where_clause_id in (select id from t_qd_where_clause where domainid ='"+qdDomain.getId().toString().trim()+"')";
						//删除functionRrole
						String delFunctionRole =" delete from t_role_function where function_id in (select distinct id from t_function start with id='"+qdDomain.getFunctionId().toString().trim()+"' connect by prior  id = parent_id )";
						//删除function
						String delFunction = "  delete from t_function where id in (select distinct id from t_function start with id='"+qdDomain.getFunctionId().toString().trim()+"' connect by prior id = parent_id )";					
						String[] sqls = new String[]{delHiscon,delDelopeWhereClause,delDelopeSimplemeasu,delDelopeComparecond,delWhereClause,delSimplemeasu,delComparecond,delFormula,delRelation,delDomain,delFunctionRole,delFunction};
						jdbcTemplate.batchUpdate(sqls);	
					}				
				}
				retInt  =  1;				
			}			
		}catch(Exception e){
			e.printStackTrace();			
		}
		return retInt;
	}
	
	
	
	/**
	 * @descripte 批量审核主题，成功返回1否则返回-1
	 * @param  strDomainId   被审核主题信息ID集
	 * @param  nFlag         审核状态 
	 * @return int
	 */
	public int setDomainFlag(String[] strDomainId,int nFlag){
		int retInt = -1;
		try{		
			if(strDomainId!=null && strDomainId.length>0){
				for(int i=0;i<strDomainId.length;i++){
					QdDomain qdDomain = (QdDomain)hibernateTemplate.get(QdDomain.class, strDomainId[i].toString().trim());
					QdMark qdMark = this.getQdMark(Long.parseLong(Integer.toString(nFlag)));					
					qdDomain.setTQdMark(qdMark);
					hibernateTemplate.update(qdDomain);
				}	
				retInt = 1;
			}		
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return retInt;
	}
	
	

	/**
	 * @descripte 批量显示和隐藏主题，成功返回1否则返回-1
	 * @param  strDomainId   被审核主题信息ID集
	 * @param  nFlag         显示状态 
	 * @return int
	 */
	public int setDomainDisplay(String[] strDomainId,int nFlag){
		int retInt = -1;
		try{		
			if(strDomainId!=null && strDomainId.length>0){
				for(int i=0;i<strDomainId.length;i++){
					QdDomain qdDomain = (QdDomain)hibernateTemplate.get(QdDomain.class, strDomainId[i].toString().trim());					
					qdDomain.setDisplayflag(nFlag);
					hibernateTemplate.update(qdDomain);
				}	
				retInt = 1;
			}		
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return retInt;
	}
	
	
	/**
	 * @descripte 新增主题信息，新增成功返回1，否则返回-1
	 * @param  strName      主题名称
	 * @param  strDescript  主题描述
	 * @param  strCatalogId 主题所属分类ID号       
	 * @return int
	 */
	public int addDomain(String strName,String strDescript,String strCatalogId){
		int retInt = -1;
		try{
			if(strName!=null && !"".equals(strName) && strCatalogId!=null && !"".equals(strCatalogId)){
				QdDomain qdDomain  = new QdDomain();
				qdDomain.setName(strName);
				
				if(strCatalogId!=null && !"".equals(strCatalogId.toString().trim())){	
					Catalog catalogId = catalogService.getCatalog(strCatalogId.toString().trim());
					qdDomain.setCatalogId(catalogId);	
				}else{
					retInt = -1;
					return retInt;				
				}
				
				qdDomain.setDescript(strDescript);	
				QdMark qdMark = getQdMark(0);				
				qdDomain.setTQdMark(qdMark);				
				
				qdDomain.setDisplayflag(1);
				
				Function function = this.addFunction(strName, strCatalogId);
				if(function!=null && function.getId()!=null){
					qdDomain.setFunctionId(function.getId().toString().trim());
					this.hibernateTemplate.save(qdDomain);
					
					function.setAddresss("/querythemes/qdDomainSearch!load4Init.action?strDomainId="+qdDomain.getId());
					this.hibernateTemplate.saveOrUpdate(function);
					retInt = 1;
				}else{
					retInt = -1;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return retInt;
	}
	
	
	/**
	 * @descripte 保存主题菜单信息 
	 * @param strName
	 * @param strParentId
	 * @param orderNo
	 * @return Function
	 */
	private Function addFunction(String strName, String strParentId){
		Function function = new Function();
		try{			
			function.setAddDate(new Date());
			if(UserUtil.getCurrentUser()!=null && UserUtil.getCurrentUser().getName()!=null){
				function.setAdderId(UserUtil.getCurrentUser().getName());
			}else{
				function.setAdderId(null);
			}
			
			function.setName(strName);
			function.setAddresss(null);
			function.setFunctionType(new Integer(0));
			function.setLeaf(true);
			function.setShow(true);
			function.setFilter(true);
			function.setOrderNum(null);			
			function.setFunctionCode(null);
			
			if(strParentId!=null && !"".equals(strParentId)){				
				Catalog parentCatalog = catalogService.getCatalog(strParentId);
				if(parentCatalog!=null && parentCatalog.getCatalogId()!=null && !"".equals(parentCatalog.getCatalogId().toString().trim())){
					String pFunctionId = parentCatalog.getFunctionId();	
					Function pFunction = null;
					if(pFunctionId!=null && !"".equals(pFunctionId.toString().trim())){
						pFunction = this.getFunction(pFunctionId);	
						if(pFunction==null || pFunction.getId()==null || "".equals(pFunction.getId().toString().trim())){
							pFunction = reBuildFunction(parentCatalog);
							if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
								parentCatalog.setFunctionId(pFunction.getId().toString().trim());
								this.hibernateTemplate.saveOrUpdate(parentCatalog);
							}
						}
					}else{
						pFunction = reBuildFunction(parentCatalog);	
						if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
							parentCatalog.setFunctionId(pFunction.getId().toString().trim());
							this.hibernateTemplate.saveOrUpdate(parentCatalog);
						}
					}					
					function.setParent(pFunction);					
				}else{
					Function pFunction = new Function();
					pFunction.setId(SysArgUtil.functionId);
					function.setParent(pFunction);
				}				
			}else{				
				Function pFunction = new Function();
				pFunction.setId(SysArgUtil.functionId);
				function.setParent(pFunction);
			}
						
			this.hibernateTemplate.saveOrUpdate(function);		
		}catch(Exception e){
			e.printStackTrace();
			function = null;			
		}
		return function;
	}
	
	
	/**
	 * @descript 重新构建菜单
	 * @param catalog
	 * @return Function
	 */
	private Function reBuildFunction(Catalog catalog){			
		Function function = new Function();
		try{
			function.setAddDate(new Date());
			if(UserUtil.getCurrentUser()!=null && UserUtil.getCurrentUser().getName()!=null){
				function.setAdderId(UserUtil.getCurrentUser().getName());
			}else{
				function.setAdderId(null);
			}
			
			function.setName(catalog.getCatalogName());
			function.setAddresss(null);
			function.setFunctionType(new Integer(1));
			function.setLeaf(false);
			function.setShow(true);
			function.setFilter(true);
			function.setOrderNum(Float.parseFloat(Long.toString(catalog.getOrderid())));			
			function.setFunctionCode(Long.toString(catalog.getOrderid()));
			
			Function pFunction = null;
			if(catalog.getParentCatalog()!=null && catalog.getParentCatalog().getCatalogId()!=null && !"".equals(catalog.getParentCatalog().getCatalogId().toString().trim())){
				String pFunctionId = catalog.getParentCatalog().getFunctionId();				
				if(pFunctionId!=null && !"".equals(pFunctionId.toString().trim())){
					pFunction = this.getFunction(pFunctionId);	
					if(pFunction==null || pFunction.getId()==null || "".equals(pFunction.getId().toString().trim())){
						pFunction = reBuildFunction(catalog.getParentCatalog());
						if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
							catalog.getParentCatalog().setFunctionId(pFunction.getId().toString().trim());
							this.hibernateTemplate.saveOrUpdate(catalog.getParentCatalog());
						}
					}
				}else{
					pFunction = reBuildFunction(catalog.getParentCatalog());
					if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
						catalog.getParentCatalog().setFunctionId(pFunction.getId().toString().trim());
						this.hibernateTemplate.saveOrUpdate(catalog.getParentCatalog());
					}
				}				
			}else{
				pFunction = new Function();
				pFunction.setId(SysArgUtil.functionId);
			}	
			
			function.setParent(pFunction);
			this.hibernateTemplate.saveOrUpdate(function);			
		}catch(Exception e){
			e.printStackTrace();
			function = null;
		}
		return function;
	}
	
	
	private Function getFunction(String functionId){
		Function function = null;
		try{
			if(functionId!=null && !"".equals(functionId.toString().trim())){
				function = (Function)hibernateTemplate.get(Function.class, functionId.toString().trim());
			}
		}catch(Exception e){
			e.printStackTrace();
			function = null;
		}
		return function;
	}
	
	
	private QdMark getQdMark(long markId){
		QdMark qdMark = null;
		try{
			if(markId>0){
				qdMark = (QdMark)hibernateTemplate.get(QdMark.class, markId);
			}else{
				qdMark = (QdMark)hibernateTemplate.get(QdMark.class, 0l);
			}
		}catch(Exception e){
			e.printStackTrace();
			qdMark = null;
		}
		return qdMark;
	}


	/**
	 * @descripte 根据主题ID号，修改主题信息，修改成功返回1，否则返回-1
	 * @param  strDomainId  被修改主题的ID号
	 * @param  strName      主题名称
	 * @param  strDescript  主题描述        
	 * @return int
	 */
	public int updateDomain(String strDomainId,String strName,String strDescript){
		int retInt = -1;
		try{
			if(strName!=null && !"".equals(strName) && strDomainId!=null && !"".equals(strDomainId)){
				QdDomain qdDomain  = (QdDomain)this.hibernateTemplate.get(QdDomain.class,strDomainId);
				qdDomain.setName(strName);
				qdDomain.setDescript(strDescript);
				Function function = this.updateFunction(qdDomain,strName);
				if(function!=null && function.getId()!=null && !"".equals(function.getId().toString().trim())){
					qdDomain.setFunctionId(function.getId().toString().trim());
					hibernateTemplate.update(qdDomain);
					
					function.setAddresss("/querythemes/qdDomainSearch!load4Init.action?strDomainId="+qdDomain.getId());
					hibernateTemplate.saveOrUpdate(function);
					retInt = 1;
				}else{
					retInt = -1;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return retInt;
	}
	
	

	private Function updateFunction(QdDomain qdDomain, String strName){		
		Function function = null;
		try{
			if(qdDomain!=null && qdDomain.getId()!=null && !"".equals(qdDomain.getId().toString().trim())){
				if(qdDomain.getFunctionId()!=null && !"".equals(qdDomain.getFunctionId().toString().trim())){
					function =(Function)hibernateTemplate.get(Function.class, qdDomain.getFunctionId().toString().trim());
					if(function==null || function.getId()==null || "".equals(function.getId().toString().trim())){
						function.setAddDate(new Date());
						if(UserUtil.getCurrentUser()!=null && UserUtil.getCurrentUser().getName()!=null){
							function.setAdderId(UserUtil.getCurrentUser().getName());
						}else{
							function.setAdderId(null);
						}
						
						function.setName(strName);
						function.setAddresss(null);
						function.setFunctionType(new Integer(0));
						function.setLeaf(true);
						function.setShow(true);
						function.setFilter(true);
						function.setOrderNum(null);			
						function.setFunctionCode(null);
						
						Function pFunction = null;
						if(qdDomain.getCatalogId()!=null && qdDomain.getCatalogId().getCatalogId()!=null && !"".equals(qdDomain.getCatalogId().getCatalogId().toString().trim())){
							String pFunctionId = qdDomain.getCatalogId().getFunctionId();				
							if(pFunctionId!=null && !"".equals(pFunctionId.toString().trim())){
								pFunction = this.getFunction(pFunctionId);	
								if(pFunction==null || pFunction.getId()==null || "".equals(pFunction.getId().toString().trim())){
									pFunction = reBuildFunction(qdDomain.getCatalogId());
									if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
										qdDomain.getCatalogId().setFunctionId(pFunction.getId().toString().trim());
										this.hibernateTemplate.saveOrUpdate(qdDomain.getCatalogId());
									}
								}
							}else{
								pFunction = reBuildFunction(qdDomain.getCatalogId());
								if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
									qdDomain.getCatalogId().setFunctionId(pFunction.getId().toString().trim());
									this.hibernateTemplate.saveOrUpdate(qdDomain.getCatalogId());
								}
							}						
							function.setParent(pFunction);						
						}
					}
				}else{
					function.setAddDate(new Date());
					if(UserUtil.getCurrentUser()!=null && UserUtil.getCurrentUser().getName()!=null){
						function.setAdderId(UserUtil.getCurrentUser().getName());
					}else{
						function.setAdderId(null);
					}
					
					function.setName(strName);
					function.setAddresss(null);
					function.setFunctionType(new Integer(0));
					function.setLeaf(true);
					function.setShow(true);
					function.setFilter(true);
					function.setOrderNum(null);			
					function.setFunctionCode(null);
					
					Function pFunction = null;
					if(qdDomain.getCatalogId()!=null && qdDomain.getCatalogId().getCatalogId()!=null && !"".equals(qdDomain.getCatalogId().getCatalogId().toString().trim())){
						String pFunctionId = qdDomain.getCatalogId().getFunctionId();				
						if(pFunctionId!=null && !"".equals(pFunctionId.toString().trim())){
							pFunction = this.getFunction(pFunctionId);	
							if(pFunction==null || pFunction.getId()==null || "".equals(pFunction.getId().toString().trim())){
								pFunction = reBuildFunction(qdDomain.getCatalogId());
								if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
									qdDomain.getCatalogId().setFunctionId(pFunction.getId().toString().trim());
									this.hibernateTemplate.saveOrUpdate(qdDomain.getCatalogId());
								}
							}
						}else{
							pFunction = reBuildFunction(qdDomain.getCatalogId());
							if(pFunction!=null && pFunction.getId()!=null && !"".equals(pFunction.getId().toString().trim())){
								qdDomain.getCatalogId().setFunctionId(pFunction.getId().toString().trim());
								this.hibernateTemplate.saveOrUpdate(qdDomain.getCatalogId());
							}
						}						
						function.setParent(pFunction);						
					}
				}
				
				function.setName(strName);
				this.hibernateTemplate.saveOrUpdate(function);				
			}
		}catch(Exception e){
			e.printStackTrace();
			function = null;
		}
		return function ;		
	}
	
	
	/**
	 * @descripte 复制主题，将源主题的表和关系定义、查询字段、主题过滤条件等信息复制至新建主题，复制成功返回1，否则返回-1
	 * @param  soureDomainId  被复制主题的ID号
	 * @param  strName        主题名称
	 * @param  strDescript    主题描述 
	 * @param  strCatalogId   主题所属分类ID号       
	 * @return int
	 */
	@SuppressWarnings({ "unchecked", "unchecked", "unchecked", "unchecked", "unchecked" })
	public int copyDomain(String soureDomainId,String strName,String strDescript,String strCatalogId){
		int retInt = -1;
		try{
			if(soureDomainId!=null && !"".equals(soureDomainId) && strCatalogId!=null && !"".equals(strCatalogId)){
				QdDomain qdDomain = new QdDomain();
				Function function = new Function();
				
				//处理主题信息
				if(strCatalogId!=null && !"".equals(strCatalogId.toString().trim())){	
					Catalog catalogId = catalogService.getCatalog(strCatalogId.toString().trim());
					qdDomain.setCatalogId(catalogId);	
				}else{
					retInt = -1;
					return retInt;				
				}					
				
				qdDomain.setDescript(strDescript);
				QdMark qdMark = getQdMark(0);				
				qdDomain.setTQdMark(qdMark);
								
				if(strName!=null && !"".equals(strName)){
					if(isExistsDomainByName(strName, strCatalogId)>0){
						retInt = -1;
					}else{
						qdDomain.setName(strName);
						function = this.addFunction(strName, strCatalogId);
						if(function!=null && function.getId()!=null){
							qdDomain.setFunctionId(function.getId().toString().trim());								
							retInt = 1;
						}else{
							retInt = -1;
						}
					}
				}else{
					retInt = -1;						
				}
				
				
					
				if(retInt>0){
					this.hibernateTemplate.save(qdDomain);
					
					function.setAddresss("/querythemes/qdDomainSearch!load4Init.action?strDomainId="+qdDomain.getId());
					hibernateTemplate.saveOrUpdate(function);
				}
					
					
				if(retInt>0){
					//复制主题和表关系
					String hql = " from QdDomainDest qdDomainDest where qdDomainDest.id.TQdDomain.id='"+soureDomainId+"'";
					List l = this.hibernateTemplate.find(hql);
					if(l!=null && l.size()>0){
						for(int i =0;i<l.size();i++){								
							QdDomainDest qdDomainDest = (QdDomainDest)l.get(i);
							QdDomainDestId qdDomainDestId =qdDomainDest.getId();
							
							QdDomainDest newQdDomainDest = new QdDomainDest();
							QdDomainDestId newQdDomainDestId = new QdDomainDestId();
							newQdDomainDestId.setTQdDest(qdDomainDestId.getTQdDest());
							newQdDomainDestId.setTQdDomain(qdDomain);
							newQdDomainDest.setId(newQdDomainDestId);								
							this.hibernateTemplate.save(newQdDomainDest);								
						}
					}
					
					//复制表关系(主题表达式)
					hql = " from QdFormula qdFormula where qdFormula.TQdDomain.id='"+soureDomainId+"'";
					l = hibernateTemplate.find(hql);
					if(l!=null && l.size()>0){
						for(int i =0;i<l.size();i++){								
							QdFormula qdFormula = (QdFormula)l.get(i);
							
							QdFormula newQdFormula = new QdFormula();
							newQdFormula.setDescript(qdFormula.getDescript());
							newQdFormula.setExpr(qdFormula.getExpr());
							newQdFormula.setTQdDomain(qdDomain);						
							this.hibernateTemplate.save(newQdFormula);								
						}
					}
					
					//复制主题查询字段
					hql = " from QdSimplemeasu qdSimplemeasu where qdSimplemeasu.TQdDomain.id='"+soureDomainId+"'";
					l = hibernateTemplate.find(hql);
					if(l!=null && l.size()>0){
						for(int i =0;i<l.size();i++){								
							QdSimplemeasu qdSimplemeasu = (QdSimplemeasu)l.get(i);	
							
							QdSimplemeasu newQdSimplemeasu = new QdSimplemeasu();
							newQdSimplemeasu.setAlias(qdSimplemeasu.getAlias());
							newQdSimplemeasu.setCol(qdSimplemeasu.getCol());
							newQdSimplemeasu.setDescript(qdSimplemeasu.getDescript());
							newQdSimplemeasu.setName(qdSimplemeasu.getName());
							newQdSimplemeasu.setOrderid(qdSimplemeasu.getOrderid());
							newQdSimplemeasu.setTQdDomain(qdDomain);								
							this.hibernateTemplate.save(newQdSimplemeasu);								
							}
					}
					
					//复制主题过滤条件
					hql = " from QdWhereClause qdWhereClause where qdWhereClause.TQdDomain.id='"+soureDomainId+"'";
					l = hibernateTemplate.find(hql);
					if(l!=null && l.size()>0){
						for(int i =0;i<l.size();i++){								
							QdWhereClause qdWhereClause = (QdWhereClause)l.get(i);
							
							QdWhereClause newQdWhereClause = new QdWhereClause();
							newQdWhereClause.setCondstr(qdWhereClause.getCondstr());
							newQdWhereClause.setName(qdWhereClause.getName());
							newQdWhereClause.setTQdDomain(qdDomain);															
							this.hibernateTemplate.save(newQdWhereClause);								
						}
					}
											
					//复制查询字段
					hql = " from QdCompareCond qdCompareCond where qdCompareCond.TQdDomain.id='"+soureDomainId+"'";
					l = hibernateTemplate.find(hql);
					if(l!=null && l.size()>0){
						for(int i =0;i<l.size();i++){								
							QdCompareCond qdCompareCond = (QdCompareCond)l.get(i);
							
							QdCompareCond newQdCompareCond = new QdCompareCond();
							newQdCompareCond.setAlias(qdCompareCond.getAlias());
							newQdCompareCond.setAutoSingleQuotation(qdCompareCond.getAutoSingleQuotation());
							newQdCompareCond.setCol(qdCompareCond.getCol());
							newQdCompareCond.setDescript(qdCompareCond.getDescript());
							newQdCompareCond.setName(qdCompareCond.getName());
							newQdCompareCond.setSql(qdCompareCond.getSql());
							newQdCompareCond.setTQdColumninfo(qdCompareCond.getTQdColumninfo());
							newQdCompareCond.setTQdComparetype(qdCompareCond.getTQdComparetype());
							newQdCompareCond.setTQdDomain(qdDomain);						
							this.hibernateTemplate.save(newQdCompareCond);								
						}
					}											
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1;
		}
		
		return retInt;
	}
	
	
	/**
	 * @descripte 根据主题ID号，删除主题及其主题配置和授权信息，删除成功返回1否则返回-1
	 * @param  strDomainId  被删主题的ID号       
	 * @return int
	 */
	public int delDomain(String strDomainId){
		int retInt = -1;
		try{
			if(strDomainId!=null && !"".equals(strDomainId) && strDomainId.length()>0){
				String[] domainId = new String[]{strDomainId};
				retInt = this.delDomain(domainId);
			}
		}catch(Exception e){
			e.printStackTrace();
		}		
		return retInt;
	}
	
	
	/**
	 * @descripte 获取主题配置的查询SQL语句
	 * @param  strDomainId  主题ID号       
	 * @return String
	 */
	@SuppressWarnings({ "unchecked", "unchecked", "unchecked", "unchecked", "unchecked", "unchecked", "unchecked" })
	public String getSQL(String strDomainId){
		String strSql = null;
		String colStr = "";
		String tableStr = "";
		String tableRelationStr = "";
		String defaultConditionStr = "";
		if(strDomainId!=null && !"".equals(strDomainId)){			
			QdDomain qdDomain = (QdDomain)hibernateTemplate.get(QdDomain.class, strDomainId);
			if(qdDomain!=null && qdDomain.getId()!=null && !"".equals(qdDomain.getId().toString().trim())){
				//主题查询列字段
				String hql = " from QdSimplemeasu qdSimplemeasu where qdSimplemeasu.TQdDomain.id='"+strDomainId+"' order by qdSimplemeasu.orderid"; 
				List l = hibernateTemplate.find(hql);
				if(l!=null && l.size()>0){
					for(int i=0;i<l.size();i++){
						String tmp = "";
						QdSimplemeasu qdSimplemeasu = (QdSimplemeasu)l.get(i);
						if(qdSimplemeasu.getCol()!=null && !"".equals(qdSimplemeasu.getCol().toString().trim())){
							tmp += " ,("+qdSimplemeasu.getCol().toString().trim()+")";
						}
						
						if(qdSimplemeasu.getName()!=null && !"".equals(qdSimplemeasu.getName().toString().trim())){
							tmp += " as "+qdSimplemeasu.getName().toString().trim();
						}
						
						colStr += tmp;
					}					
				}
				
				//主题关联表信息
				hql = " from QdDomainDest qdDomainDest where qdDomainDest.id.TQdDomain.id='"+strDomainId+"' "; 
				l = hibernateTemplate.find(hql);
				if(l!=null && l.size()>0){					
					for(int i=0;i<l.size();i++){
						QdDomainDest qdDomainDest = (QdDomainDest)l.get(i);
						if(qdDomainDest!=null && qdDomainDest.getId().getTQdDest().getName()!=null && !"".equals(qdDomainDest.getId().getTQdDest().getName().toString().trim())){
							tableStr += " ,"+qdDomainDest.getId().getTQdDest().getName().toString().trim();
						}
					}
				}
				
				
				//主题表关系(主题表达式)
				hql = " from QdFormula qdFormula where qdFormula.TQdDomain.id='"+strDomainId+"' "; 
				l = hibernateTemplate.find(hql);
				if(l!=null && l.size()>0){
					QdFormula qdFormula = (QdFormula)l.get(0);
					if(qdFormula!=null && qdFormula.getExpr()!=null && !"".equals(qdFormula.getExpr().toString().trim())){
						tableRelationStr += " "+qdFormula.getExpr().toString().trim();
					}							
				}
				
				
				//主题过滤条件
				hql = " from QdWhereClause qdWhereClause where qdWhereClause.TQdDomain.id='"+strDomainId+"' "; 
				l = hibernateTemplate.find(hql);
				if(l!=null && l.size()>0){
					for(int i=0;i<l.size();i++){
						QdWhereClause qdWhereClause = (QdWhereClause)l.get(i);
						if(qdWhereClause!=null && qdWhereClause.getCondstr()!=null && !"".equals(qdWhereClause.getCondstr().toString().trim())){
							defaultConditionStr += " or ("+qdWhereClause.getCondstr().toString().trim()+" )";
						}						
					}						
				}
								
				if(colStr!=null && !"".equals(colStr.toString().trim()) && tableStr!=null && !"".equals(tableStr.toString().trim())){
					colStr = colStr.substring(2);
					tableStr = tableStr.substring(2);
					strSql = " select " + colStr +" from " +tableStr +" where 1=1 ";
					
					if(tableRelationStr!=null && !"".equals(tableRelationStr.toString().trim())){
						strSql += " and  " +tableRelationStr;
					}
					
					if(defaultConditionStr!=null && !"".equals(defaultConditionStr.toString().trim())){
						defaultConditionStr = defaultConditionStr.substring(3);
						strSql += " and (" + defaultConditionStr +" )";
					}					
				}
				
			}
		}
		return strSql;
	}
	
	
	/**
	 * @descripte 获取主题配置结果数据
	 * @param  strDomainId  主题ID号       
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List getData(String strDomainId){
		List retList = null;
		try{
			if(strDomainId!=null && strDomainId.toString().trim().length()>0){
				String sql = this.getSQL(strDomainId);
				if(sql!=null && sql.toString().trim().length()>0){
					sql+=" and rownum<101 ";
					retList = this.jdbcTemplate.queryForList(sql);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			retList = null;
		}
		return retList;
	}
	
	/**
	 * @descripte 获取主题访问的URL
	 * @param  strDomainId  主题ID号       
	 * @return String
	 */
	public String getUrl(String strDomainId){
		String path = null;
		if(strDomainId!=null && !"".equals(strDomainId)){
		    path = ServletActionContext.getRequest().getContextPath();
			path += "/querythemes/qdDomainSearch!load4Init.action?strDomainId="+strDomainId;
		}		
		return path;
	}
	
	
	
	/**
	 * @descripte 测试SQL语句 成功返回1，否则返回-1
	 * @param  strSql  SQL语句       
	 * @return int 
	 */
	public int testSql(String strSql){
		int retInt = -1;
		try{
			if(strSql!=null && !"".equals(strSql.toString().trim())){
				jdbcTemplate.queryForList(strSql);
				retInt = 1;
			}		
		}catch(Exception e){
			e.printStackTrace();
			retInt = -1;
		}
		return retInt;
	}
	
	
	/**
	 * @descripte 校验SQL语句 成功返回true，否则返回错误信息代码
	 * @param  strSql  SQL语句       
	 * @return String[]  String[0]  true 成功 false 失败
	 *                   String[1]  String[0]=true时为空，String[0]=false时为错误信息
	 */
	public String[] CheckSql(String strSql){
		String[] retArr =new String[2];
		try{
			if(strSql!=null && !"".equals(strSql.toString().trim())){
				jdbcTemplate.execute(strSql);
				retArr[0]="true";
				retArr[1]="";
			}else{
				retArr[0]="false";
				retArr[1]="SQL为空";
			}
		}catch(Exception e){
			e.printStackTrace();
			String strErrMsg = e.getMessage();
			if (strErrMsg.substring(0,4) == "ORA-"){
				strErrMsg = strErrMsg.substring(10);				
			}
			retArr[0]="false";
			retArr[1]=strErrMsg;
		}
		return retArr;
	}
	
	
	/**
	 * @descript 查询主题信息
	 * @param qdDomain 主题查询条件
	 * @param pageNo  页面
	 * @param pageSize 每页显示记录数
	 * @return Page
	 */
	public Page getQdDomainList(QdDomain qdDomain, int pageNo, int pageSize){
		if (pageNo <= 0) pageNo = 1;		
		StringBuffer sb = new StringBuffer(" from QdDomain qdDomain where 1=1 ");
		Map params = new HashMap();
		if(qdDomain!=null){
			if(qdDomain.getCatalogId()!=null && qdDomain.getCatalogId().getCatalogId()!=null && !"".equals(qdDomain.getCatalogId().getCatalogId().toString().trim())){
				sb.append(" and (qdDomain.catalogId.catalogId = :catalogId  )");
				params.put("catalogId", qdDomain.getCatalogId().getCatalogId().toString().trim());
			}
			
			if(qdDomain.getCatalogId()!=null && qdDomain.getCatalogId().getCatalogName()!=null && !"".equals(qdDomain.getCatalogId().getCatalogName().toString().trim())){
				sb.append(" and (qdDomain.catalogId.catalogName like :catalogName  )");
				params.put("catalogName", "%"+qdDomain.getCatalogId().getCatalogName().toString().trim()+"%");
			}
			
			if(qdDomain.getName()!=null && !"".equals(qdDomain.getName().toString().trim())){
				sb.append(" and (qdDomain.name like :name  )");
				params.put("name", "%"+qdDomain.getName().trim()+"%");
			}
		}
		HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, params, null, pageNo, pageSize);
		Page page = (Page)hibernateTemplate.execute(action);		
		return page;
	}

	

}
